package com.dx.mes.service.query.service;

import com.dx.common.table.ppt.*;
import com.dx.mes.common.dao.*;
import com.dx.mes.common.table.rtnBean.NotFoundRtnBeen;
import com.dx.mes.common.table.rtnBean.SimpleRtnBeen;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.query.service.IFipinqworService;
import com.dx.mes.facade.query.tx.Fipinqwor.*;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

import com.dx.mes.common.transcoder.util.LogUtils;

import static com.dx.mes.common.bean.def.GenericDef.*;


@Service("fipinqworService")
@SuppressWarnings({"unchecked"})
public class FipinqworService implements IFipinqworService {
	private LogUtils logUtils;
	private static final String TX_NAME = "FIPINQWOR";

	@Autowired
	private IRetBoxDao retBoxDao;
	@Autowired
	private IFiplstworDao lstWorDao;
	@Autowired
	private IRetWODao retWODao;
	@Autowired
	private IRetPrdInfoDao retPrdInfoDao;
	@Autowired
	private IRetShipNoticeDao retShipNoticeDao;
	@Autowired
	private IRetPrdInDao retPrdInDao;
	@Autowired
	private IBisDataDao bisDataDao;
	@Autowired
	private IBisPathiDao bisPathiDao;
	
	public String subMainProc(String evt_no,String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(FipinqworService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FipinqworService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");
		
		String strOutTrx = null;
		FipinqworI inTrx = new FipinqworI();
		FipinqworO outTrx = new FipinqworO();
		
		outTrx.setTrx_id(TX_NAME);
		outTrx.setType_id(TRX_OUT);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		
		try{
		   inTrx = JacksonUtil.fromJson(strInMsg, FipinqworI.class);
		   char action_flgAry[] = inTrx.getAction_flg().toCharArray();
		   char action_flg = action_flgAry[0];
		   switch (action_flg) {
		      case 'I':
			    findWorderById(inTrx.getWorder_id(),outTrx);
			    break;
		      case 'S':
			    sumWoInfo(inTrx,outTrx);
			    break;
		      case 'L':
			    listWoBoxInfo(inTrx,outTrx);
			    break;
		      case 'P':
		        getPrdListInfo(inTrx,outTrx);
		    	break;
		      default:
				outTrx.setRtn_code(RETURN_CODE_SET_ERROR);
				outTrx.setRtn_mesg("mapping no action_flg ,error");
		   }
			if( RETURN_CODE_OK.equals(outTrx.getRtn_code()) ){
				retBoxDao.flushCurSession();
			}else{
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}	
		}catch (Exception ex) {
			TransactionAspectSupport.currentTransactionStatus()
				.setRollbackOnly();
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			logUtils.error(Util.stackTraceToString(ex));
        } finally {
        	strOutTrx = JacksonUtil.toJSONStr(outTrx);
        	logUtils.info("[OutTrx:" + strOutTrx + "]");
         }
		return strOutTrx;
	}

	 private void getPrdListInfo(FipinqworI inTrx,FipinqworO outTrx){
		 
			List<Ret_prd_info> retPrdInfoList = null;
			List<FipinqworO5> oaryList = new ArrayList<FipinqworO5>();
			
				String hql = " FROM Ret_prd_info where wo_id_fk=:wo_id_fk";
				try {
					Query query = retPrdInfoDao.getCrSession().createQuery(hql);
					query.setString("wo_id_fk", inTrx.getWorder_id());
					retPrdInfoList = query.list();
				} catch (Exception ex) {
					logUtils.error("read RET_PRD_INFO ERROR:" + ex.getMessage());
					logUtils.error(Util.stackTraceToString(ex));
				}

			for (Ret_prd_info ret_prd_info : retPrdInfoList) {
				FipinqworO5 oary5 = new FipinqworO5();
				oary5.setPrd_seq_id(ret_prd_info.getPrd_seq_id());
				oary5.setFab_sn(ret_prd_info.getFab_sn());
				oary5.setSlot_no(ret_prd_info.getSlot_no());
				oary5.setPrd_stat(ret_prd_info.getPrd_stat());
				oary5.setBox_id_fk(ret_prd_info.getBox_id_fk());
				oary5.setPrd_grade(ret_prd_info.getPrd_grade());
				String pathId = PROC_WAIT.equals(ret_prd_info.getPrd_stat()) ? ret_prd_info.getNx_path_id_fk() : ret_prd_info.getCr_path_id_fk();
				String pathVer = PROC_WAIT.equals(ret_prd_info.getPrd_stat()) ? ret_prd_info.getNx_path_ver_fk() : ret_prd_info.getCr_path_ver_fk();
				Bis_pathiId id = new Bis_pathiId();
				id.setPath_id(pathId);
				id.setPath_ver(pathVer);
				Bis_pathi bis_pathi = bisPathiDao.get(id);
				if(bis_pathi !=null){
					if(bis_pathi.getPath_cate().equals(PATH_TYPE_REWK)){
						oary5.setOqc_skip_flg(_YES);
					}else{
						oary5.setOqc_skip_flg(_NO);
					}
				}
				oary5.setBnk_flg(ret_prd_info.getBnk_flg());
				if (ret_prd_info.getPrd_stat().equals("INPR")) {
					oary5.setCr_ope_id(ret_prd_info.getCr_ope_id_fk());
					oary5.setCr_ope_no(ret_prd_info.getCr_ope_no_fk());
					oary5.setCr_ope_ver(ret_prd_info.getCr_ope_ver_fk());
					oary5.setCr_path_id(ret_prd_info.getCr_path_id_fk());
					oary5.setCr_path_ver(ret_prd_info.getCr_path_ver_fk());
					oary5.setCr_proc_id_fk(ret_prd_info.getCr_proc_id_fk());
				} else {
					oary5.setCr_ope_id(ret_prd_info.getNx_ope_id_fk());
					oary5.setCr_ope_no(ret_prd_info.getNx_ope_no_fk());
					oary5.setCr_ope_ver(ret_prd_info.getNx_ope_ver_fk());
					oary5.setCr_path_id(ret_prd_info.getNx_path_id_fk());
					oary5.setCr_path_ver(ret_prd_info.getNx_path_ver_fk());
					oary5.setCr_proc_id_fk(ret_prd_info.getNx_proc_id_fk());
				}
				oary5.setTool_id_fk(ret_prd_info.getTool_id_fk());
				oary5.setLot_id_fk(ret_prd_info.getLot_id());
				oary5.setMdl_id_fk(ret_prd_info.getMdl_id_fk());
				oary5.setSo_id_fk(ret_prd_info.getSo_id_fk());
				oary5.setWo_id_fk(ret_prd_info.getWo_id_fk());
				oary5.setMtrl_box_id(ret_prd_info.getMtrl_box_id_fk());
				oaryList.add(oary5);
			}
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			outTrx.setOary5(oaryList);
			outTrx.setOary5_cnt(oaryList.size());
			
	    }
	 
	private void listWoBoxInfo(FipinqworI inTrx,FipinqworO outTrx) {
		
		String hql = "FROM Ret_box where wo_id_fk =:wo_id_fk ";
		Query query = retBoxDao.getCrSession().createQuery(hql);
		query.setString("wo_id_fk", inTrx.getWorder_id());
		List<Ret_box> retBoxList = query.list();
		List<FipinqworOB> oaryList = new ArrayList<FipinqworOB>();
		for (Ret_box ret_box : retBoxList) {
			FipinqworOB oary = new FipinqworOB();
			oary.setBox_id(ret_box.getBox_id());
			//oary.setLot_id(ret_box.getLot_id_fk());
			oary.setOpe_id(ret_box.getNx_ope_id_fk());
			oary.setOpe_ver(ret_box.getNx_ope_ver_fk());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	/**
	 * Query many wo's info summary
	 */
	public void sumWoInfo(FipinqworI inTrx,FipinqworO outTrx) {
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);

		rtnBeen = sumWoInfoReal(inTrx.getWorder_id(),outTrx);
		if (rtnBeen.getlRc() != _NORMAL) {
			outTrx.setRtn_code(String.valueOf(rtnBeen.getlRc()));
			outTrx.setRtn_mesg(rtnBeen.getMsgBuf());
		} else {
			outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
			outTrx.setRtn_mesg(RETURN_MESG_OK);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	private SimpleRtnBeen sumWoInfoReal(String wo_id,FipinqworO outTrx) {
		Ret_wo ret_so = new Ret_wo();
		FipinqworOA out1 = new FipinqworOA();;
		String so_id = "";

		// Get wo
		Ret_wo ret_wo = new Ret_wo();
		ret_wo = retWODao.get(wo_id);
		if (null == ret_wo) {
			String gszMsgBuf = new NotFoundRtnBeen(wo_id + "[W]", Ret_wo.class).toString();
			return new SimpleRtnBeen(E_RET_WO + E_READ_NOT_FOUND, gszMsgBuf);
		}
		out1.setWo_tb(ret_wo);

		// Get so
		so_id = ret_wo.getSo_id();
		if(!StringUtils.isEmpty(so_id)){
			ret_so = retWODao.get(so_id);
			if(ret_so!=null){
				out1.setSo_tb(ret_so);
			}
		}
		outTrx.setOut1(out1);

		return new SimpleRtnBeen(_NORMAL);
	}

	public void findWorderById(String wo_id,FipinqworO outTrx) {
		Ret_wo retWo = new Ret_wo();
		try {

		} catch (Exception ex) {
			logUtils.error(Util.stackTraceToString(ex));
			outTrx.setRtn_code("0000001");
			outTrx.setRtn_mesg(ex.getMessage());
		}
		String querySql = " from Ret_wo where wo_id= '" + wo_id + "'";
		List<Ret_wo> retWoList = lstWorDao.find(querySql);
		outTrx.setRtn_code("0000000");
		outTrx.setRtn_mesg("success");
		if (retWoList.size() > 0) {
			retWo = retWoList.get(0);
			outTrx.setWo_id(retWo.getWo_id());
			outTrx.setWo_cate(retWo.getWo_cate());
			outTrx.setWo_dsc(retWo.getWo_dsc());
			outTrx.setWo_typ(retWo.getWo_typ());
			outTrx.setWo_prty(retWo.getWo_prty());
			outTrx.setWo_stat(retWo.getWo_stat());
			outTrx.setSo_id(retWo.getSo_id());
			outTrx.setMdl_id_fk(retWo.getMdl_id_fk());
			outTrx.setPln_stb_date(retWo.getPln_stb_timestamp().toString());
			outTrx.setPln_cmp_date(retWo.getPln_cmp_timestamp().toString());
			outTrx.setErp_path_id(retWo.getErp_path_id());
			outTrx.setErp_path_ver(retWo.getErp_path_ver());
			outTrx.setErp_bom_id(retWo.getErp_bom_id());
			outTrx.setPath_id_fk(retWo.getPath_id_fk());
			outTrx.setPath_ver_fk(retWo.getPath_ver_fk());
			outTrx.setStr_ope_no(retWo.getStr_ope_no());
			outTrx.setPln_prd_qty(retWo.getPln_prd_qty());
			outTrx.setRl_prd_qty(retWo.getRl_prd_qty());
			outTrx.setComp_prd_qty(retWo.getComp_prd_qty());
			outTrx.setWh_in_prd_qty(retWo.getWh_in_prd_qty());
			outTrx.setScrp_prd_qty(retWo.getScrp_prd_qty());
			outTrx.setDest_shop(retWo.getDest_shop());
			outTrx.setPlant_id(retWo.getPlant_id());
			/*outTrx.setSwh_cnt_flg(retWo.getSwh_cnt_flg());
			outTrx.setOpe_eff_flg(retWo.getOpe_eff_flg());
			outTrx.setVcr_flg_fk(retWo.getVcr_flg_fk());*/
			outTrx.setEvt_user(retWo.getEvt_usr());
			outTrx.setEvt_timestamp(retWo.getEvt_timestamp().toString());
			/*outTrx.setMdl_cate_fk(retWo.getMdl_cate_fk());*/
		}
	}

	private Integer fmtInt(Integer val){
		return val == null ? 0 : val;
	}
	
}
